package com.farah.lease.common.utils;

import com.farah.lease.common.exception.LeaseException;
import com.farah.lease.common.login.LoginUser;
import com.farah.lease.common.login.LoginUserHolder;
import com.farah.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @Author 不爱跑步的法拉韶
 * @Date 2024-06-24__09:20
 * @Description JWT工具类
 **/
public class JwtUtil {
    /**
     * 60 * 60 * 1000Lms过期时间一个小时
     */
    private static final long TOKEN_EXPIRATION = 2*60 * 60 * 1000L;
    /**
     * 秘钥
     */
    private static final SecretKey TOKEN_SIGN_KEY = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());


    /**
     * 创建token-JWT
     * @param userId 用户id
     * @param username 用户名
     * @return
     */
    public static String createToken(Long userId, String username) {
        return Jwts.builder().
                setSubject("USER_INFO").
                setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRATION)).
                claim("userId", userId).
                claim("username", username).
                signWith(TOKEN_SIGN_KEY).
                compact();
    }

    /**
     * 解析token的方法
     * @param token 需要
     * @return Claims对象
     */
    public static Claims parseToken(String token){
     if(token==null){
         throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
     }
     try{
         JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(TOKEN_SIGN_KEY).build();
         Claims claims = jwtParser.parseClaimsJws(token).getBody();
         LoginUserHolder.setLoginUser(new LoginUser(claims.get("userId",Long.class),claims.get("username",String.class)));
         //获取用户id
         return jwtParser.parseClaimsJws(token).getBody();
     }catch(ExpiredJwtException e){
         //token过期
         throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
     }catch(JwtException e){
         //token不正确
         throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
     }
    }

}
